const axios = require('axios');
const path = require('path');
// 车辆配置信息：配置名称，配置id, 品牌id，价格，销售状态，保险，能源类型
class CarConfig {
    constructor(
        {
            car_name,
            car_id,
            brand_id,
            model_id,
            dealerPrice,
            decade,
            batchId,
            isSale
        }
    ) {
        this.car_name = car_name
        this.car_id = car_id
        this.brand_id = brand_id
        this.model_id = model_id
        this.dealerPrice = dealerPrice
        this.decade = decade
        this.batchId = batchId
        this.isSale = isSale
    }
}
const headers = {
    Host: 'sapi.16888.com',
    Connection: 'keep-alive',
    'xweb_xhr': 1,
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/6.8.0(0x16080000) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF MacWechat/3.8.7(0x13080710) XWEB/1191',
    Accept: '*/*',
    'Sec-Fetch-Site': 'cross-site',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    Referer: 'https://servicewechat.com/wx4cface15c95f3a46/6/page-frame.html',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Content-Type': 'application/json'
};
const carListPath = path.join(__dirname, 'car.json');
const carList = require(carListPath).data;

// sleep函数，用于模拟延迟
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
// 主异步函数
(async function fetchCarData(carList) {
    try {
        const results = [];

        for (const car of carList) {
            try {
                // 发起请求
                const url = 'https://sapi.16888.com/wxapp/wx4cface15c95f3a46/app.php';
                const params = {
                    mod: 'price',
                    extra: 'styleInfo',
                    letter: 'cd',
                    sid: car.id, // 上层的styleId
                };
                const response = await axios.get(url, {
                    params: {
                        ...params,
                        brandId: car.id
                    },
                    headers
                });
                if (response.status === 200) {
                    const data = response.data.data;

                    data.carList.forEach(carItem => {
                        carItem.list.forEach(config => {
                            results.push(config);
                        })
                    })
                } else {
                    console.warn(`Request failed with status code ${response.status} for ID: ${car.id}`);
                }
            } catch (error) {
                console.error(`Error fetching URL for ID: ${car.id}, ${error.message}`);
            }

            // 模拟延迟
            await sleep(300); // 假设每次请求之间延迟500毫秒
        }

        // 如果需要写入文件的操作可以在这里进行
        const json = { data: results };
        const fs = require('fs');
        fs.writeFileSync(path.join(__dirname, 'carConfigList.json'), JSON.stringify(json, null, 2));

    } catch (error) {
        console.error(`Overall error during fetch operations: ${error.message}`);
    }
})(carList); // 传入carList并立即执行这个异步函数

